﻿namespace HCore
{
    public partial class Server
    {
        private class ServerLobbyState : State<Server>
        {
            public ServerLobbyState(Server owner) : base(owner)
            {
            }

            public override void Enter()
            {
                _owner.Log("Enter Lobby");
                _owner._networkMgr.Register(PacketType.Hello, HandleHello);
            }

            private void HandleHello(SessionPacket sessionPacket)
            {
                var networkMgr = _owner._networkMgr;
                var clientProxies = _owner._clientProxies;
                InputMemoryBitStream intput = sessionPacket.input;
                uint sessionId = sessionPacket.sessionId;

                if (clientProxies.TryGetValue(sessionId, out var proxy))
                {
                    return;
                }

                // 欢迎新玩家
                string name = intput.ReadString();
                _owner.Log("Welcome:" + name);
                int newPlayerId = ++_owner._nextPlayerId;
                proxy = new ClientProxy(newPlayerId, name);
                // 向新玩家确认和介绍老玩家
                OutputMemeryBitStream output = new OutputMemeryBitStream();
                output.WriteByte(PacketType.Hello);
                output.WriteInt(proxy.playerId);
                output.WriteInt(clientProxies.Count);
                // 向新玩家介绍老玩家
                foreach (var kv in clientProxies)
                {
                    output.WriteInt(kv.Value.playerId);
                    output.WriteString(kv.Value.name);
                }

                clientProxies.Add(sessionId, proxy);
                networkMgr.Send(output.GetBuffer(), output.GetByteLength(), sessionId);
                // 向其他玩家介绍新玩家
                foreach (var kv in clientProxies)
                {
                    if (kv.Key.Equals(sessionId))
                    {
                        continue;
                    }

                    output = new OutputMemeryBitStream();
                    output.WriteByte(PacketType.Introduce);
                    output.WriteInt(proxy.playerId);
                    output.WriteString(proxy.name);
                    _owner.Log("Introduce:" + proxy.name + " to " + kv.Value.name + " " + kv.Key);
                    networkMgr.Send(output.GetBuffer(), output.GetByteLength(), kv.Key);
                }
            }

            public override void Execute()
            {
                // 检查玩家已满，满了向所有玩家发起开始战斗
                if (_owner._nextPlayerId < _owner._lobbyPlayerNum)
                {
                    return;
                }

                var stateMachine = _owner._stateMachine;
                stateMachine.ChangeState<ServerBattleState>();
            }

            public override void Exit()
            {
                _owner._networkMgr.Unregister(PacketType.Hello);
                _owner.Log("Exit Lobby");
            }
        }
    }
}